const { json } = require("express");
const { Server } = require("socket.io");
var db = require("../db/db.js");
const { jwtCheck } = require("../module/jwt");

let user = [];
module.exports = (server) => {
  const io = new Server(server);
  io.on("connection", (socket) => {
    console.log("有人进入", socket.id);
    socket.on("token", async (data) => {
      jwtCheck(data)
        .then(async (res) => {
          let userinfo = await db.query("select * from user where id=?", [
            res.id,
          ]);
         // console.log("userinfo", userinfo);
          let obj = {
            id: socket.id,
            name: userinfo[0].nickname,
            avatar: userinfo[0].avatar,
          };
          user.push(obj);
          console.log("user", user);
          io.emit("all", user);
        })
        .catch((err) => {
          socket.emit("err", 401);
        });

      //
    });
    // 用户聊天
    socket.on("message", (msg) => {
      // 获取发信人的信息
      let send = user.find((item) => item.id === socket.id);
      // 将发信人的信息一并发过去
      if(send){
        io.sockets.to(msg.id).emit("news", {
        message: msg.message,
        avatar: send.avatar,
        name:send.name,
        id:socket.id
      });
      }
      
    });
    socket.on("disconnect", function () {
      // 服务已断开，等待重新连接
      console.log("用户断开连接", socket.id);
      user.forEach((item,index)=>{
        if(item.id===socket.id){
          user.splice(index, 1);
          io.emit('all',user)
        }
      })
      console.log('user',user)
    });
  });
};

